package com.gc.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gc.Common.result.ResultUtils;
import com.gc.Common.utils.EmptyUtils;
import com.gc.entity.Cart;
import com.gc.entity.Type;
import com.gc.service.ICartService;
import com.gc.service.ITypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Yuyingying
 * @since 2024-09-05
 */
@RestController
@RequestMapping("/cart")

public class CartController {

    @Autowired
    ICartService service;

    @RequestMapping("/getList")
    public Object getList(Cart cart){
        List<Cart> list = service.getList(cart);
        //返回结果
        return ResultUtils.returnDataSuccess(list);
    }

    @RequestMapping("/add")
    public Object add(Cart cart){

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("pid",cart.getPid());
        queryWrapper.eq("desk_id",cart.getDeskId());


        Cart one = service.getOne(queryWrapper);
        if (EmptyUtils.isNotEmpty(one)) {
            //更新数量
            one.setNum(one.getNum() + cart.getNum());
            //当数量为0时，删除此菜品
            if (one.getNum() == 0) {
                //执行删除的方法
                if (service.removeById(one)) {
                    return ResultUtils.returnSuccess();
                } else {
                    return ResultUtils.returnFail("更新数量失败");
                }
            } else {
                //执行更新的方法
                if (service.updateById(one)) {
                    return ResultUtils.returnSuccess();
                } else {
                    return ResultUtils.returnFail("更新数量失败");
                }
            }
        } else {
            //添加
            if (service.save(cart)) {
                return ResultUtils.returnSuccess();
            } else {
                return ResultUtils.returnFail("添加失败");
            }
        }
    }

    @RequestMapping("/del")
    public Object del(Integer deskId){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("desk_id",deskId);
        if(service.remove(queryWrapper)){
            return ResultUtils.returnSuccess();
        }else{
            return ResultUtils.returnFail("删除失败");
        }
    }

}